﻿/*
 * This file is part of MonoStrategy.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://monostrategy.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MonoStrategy.RenderSystem;

namespace MonoStrategy
{
    public class VisualBuildTask
    {
        private static readonly LinkedList<VisualBuildTask> m_Tasks = new LinkedList<VisualBuildTask>();

        private List<RenderableVisual> m_Renderables = new List<RenderableVisual>();
        private LinkedListNode<VisualBuildTask> m_Node = null;

        public BuildTask Task { get; private set; }
        public BaseBuilding Building { get { return Task.Building; } }
        public TerrainRenderer Renderer { get; private set; }

        public static VisualBuildTask GetBuildTaskAt(Point inPosition)
        {
            foreach (var task in m_Tasks)
            {
                var building = task.Task.Building;
                Rectangle rect = new Rectangle(building.Position.XGrid, building.Position.YGrid, building.Config.GridWidth, building.Config.GridHeight);

                if (rect.Contains(inPosition))
                    return task;
            }

            return null;
        }

        private VisualBuildTask(TerrainRenderer inRenderer, BuildTask inTask)
        {
            inTask.OnStateChanged += Map_OnBuildTaskStateChanged;
            Renderer = inRenderer;
            Task = inTask;

            Map_OnBuildTaskStateChanged(inTask);
        }

        public static void Assign(TerrainRenderer inRenderer, BuildTask inTask)
        {
            if (inTask.UserContext != null)
                throw new InvalidOperationException();

            var visual = new VisualBuildTask(inRenderer, inTask);

            inTask.UserContext = visual;
            visual.m_Node = m_Tasks.AddLast(visual);
        }

        public static void Detach(BuildTask inTask)
        {
            if (inTask.UserContext == null)
                return;

            VisualBuildTask visualizer = inTask.UserContext as VisualBuildTask;

            visualizer.ReleaseRenderables();
            m_Tasks.Remove(visualizer.m_Node);

            visualizer.m_Node = null;
            inTask.UserContext = null;
        }

        private RenderableAnimationClass CreateBuildingMarker(int inPosX, int inPosY)
        {
            var anim = Renderer.CreateAnimation("Other", new PositionTracker() { Position = CyclePoint.FromGrid(inPosX, inPosY) });

            anim.Play("BuildMarker");

            return anim;
        }

        private void ReleaseRenderables()
        {
            foreach (var renderable in m_Renderables)
            {
                Renderer.RemoveVisual(renderable);
            }

            m_Renderables.Clear();
        }

        void Map_OnBuildTaskStateChanged(BuildTask inTask)
        {
            if (!inTask.IsGraded)
            {
                // mark grading area
                var pos = inTask.Building.Position.ToPoint();

                m_Renderables.Add(CreateBuildingMarker(pos.X, pos.Y));
                m_Renderables.Add(CreateBuildingMarker(pos.X + inTask.Config.GridWidth, pos.Y));
                m_Renderables.Add(CreateBuildingMarker(pos.X + inTask.Config.GridWidth, pos.Y + inTask.Config.GridHeight));
                m_Renderables.Add(CreateBuildingMarker(pos.X, pos.Y + inTask.Config.GridHeight));
            }
            else if (!inTask.IsBuilt)
            {
                // animate build progress
                RenderableAnimationClass renderable = Renderer.CreateAnimation(Building.Config.AnimationClass, Building);

                renderable.BuildingProgress = 0;

                ReleaseRenderables();

                m_Renderables.Add(renderable);

                inTask.OnProgressChanged += (task, progress) => {
                    renderable.BuildingProgress = progress;
                };
            }
            else if (!inTask.IsCompleted)
            {
                // missing settler or tool?
                ReleaseRenderables();

                m_Renderables.Add(Renderer.CreateAnimation(Building.Config.AnimationClass, Building));
            }
            else
            {
                ReleaseRenderables();

                Detach(inTask);
            }
        }
    }
}
